var fs = require('fs');
var mongoose = require('mongoose');

/**
 * 
 * Manager class for initiating Mongoose connection and schemas. Allows for
 * additional schemas to be defined and accessed by an application imlementing
 * {@link Server}. The mongoose connection is stored at 'server.db'. 
 * 
 * @class ModelManager
 * @author jmanero
 * 
 * @requires fs
 * @requires mongoose
 * 
 * @constructor
 * @param {Server}
 *            server
 * @param {Function}
 *            callback
 * 
 */
var ModelManager = function(server, callback) {
	this.server = server;
	this.callback = callback;
	modelManager = this;

	fs.readFile('./Configuration/modelManager.json', function(e, content) {
		if (e)
			throw e;

		modelManager.config = JSON.parse(content);

		server.db = mongoose.createConnection('mongodb://'
				+ modelManager.config.server + ':' + modelManager.config.port
				+ '/' + modelManager.config.database);

		if (typeof (modelManager.callback) == 'function') {
			modelManager.callback();
		}
	});

	server.Models = {};
	return this;
};

/**
 * 
 * Loads a Mongoose Model. Model object is stored at 'server.Models[name]'.
 * 
 * @param {String} module
 */
ModelManager.prototype.add = function(module) {
	var model = require(this.config.modelPath + '/' + module);
	if (!model.name || !model.schema)
		throw TypeError("ModelManager.add requires properties name and schema");

	this.server.Models[model.name] = server.db.model(model.name, model.schema);
	this.server.Models[model.name].startup();
};

/**
 * 
 * Fetch the MongoDB native connection object
 * 
 * @returns {mongodb.Connection}
 */
ModelManager.prototype.native = function() {
	return this.server.db.db;
};

module.exports = ModelManager;
